/**
 * 全局音频播放控制条
 * 显示在底部导航栏上方，支持播放控制和返回详情页
 */

import React, { useEffect, useRef } from 'react';
import {
  View,
  Text,
  TouchableOpacity,
  StyleSheet,
  Platform,
  Animated,
  Easing,
} from 'react-native';
import Icon from 'react-native-vector-icons/Ionicons';
import { useNavigationState } from '@react-navigation/native';
import { useAudioPlayer } from '../context/AudioPlayerContext';
import voiceService from '../services/voiceService';
import { COLORS, SPACING } from '../styles/constants';

const GlobalAudioPlayer = () => {
  const {
    currentAttraction,
    isPlaying,
    isPaused,
    resume,
    pause,
    stop,
    navigateToCurrentAttraction,
  } = useAudioPlayer();

  // 获取当前路由名称
  const currentRouteName = useNavigationState(state => {
    if (!state) return null;
    const route = state.routes[state.index];
    return route.name;
  });

  // 动画值：控制条从底部滑入/滑出
  const slideAnim = useRef(new Animated.Value(0)).current;
  // 图片旋转动画
  const rotateAnim = useRef(new Animated.Value(0)).current;
  const spinAnimationRef = useRef(null);

  // 是否显示控制条：有播放内容且不在播放页时显示
  const shouldShow =
    currentAttraction !== null && currentRouteName !== 'AttractionDetail';

  // 控制条滑入/滑出动画
  useEffect(() => {
    if (shouldShow) {
      // 滑入
      Animated.timing(slideAnim, {
        toValue: 1,
        duration: 300,
        useNativeDriver: true,
      }).start();
    } else {
      // 滑出
      Animated.timing(slideAnim, {
        toValue: 0,
        duration: 200,
        useNativeDriver: true,
      }).start();
    }
  }, [shouldShow, slideAnim]);

  // 图片旋转动画（播放时旋转）
  useEffect(() => {
    if (isPlaying && shouldShow) {
      // 停止之前的动画
      if (spinAnimationRef.current) {
        spinAnimationRef.current.stop();
      }

      // 创建循环旋转动画
      spinAnimationRef.current = Animated.loop(
        Animated.timing(rotateAnim, {
          toValue: rotateAnim._value + 1,
          duration: 5000, // 5秒转一圈
          useNativeDriver: true,
          easing: Easing.linear,
        }),
      );

      spinAnimationRef.current.start();
    } else {
      // 暂停时停止动画
      if (spinAnimationRef.current) {
        spinAnimationRef.current.stop();
        spinAnimationRef.current = null;
      }
    }

    return () => {
      if (spinAnimationRef.current) {
        spinAnimationRef.current.stop();
      }
    };
  }, [isPlaying, shouldShow, rotateAnim]);

  // 处理播放/暂停按钮点击
  const handlePlayPause = async () => {
    try {
      
      if (isPlaying) {
        // 暂停播放
        await voiceService.pauseAudio();
        pause(); // 更新Context状态
      } else {
        // 恢复播放或导航到详情页
        if (isPaused && voiceService.currentSound) {
          // 如果是暂停状态且有音频对象，恢复播放
          await voiceService.resumeAudio(
            error => {
              if (error) {
                console.error('❌ [GlobalAudioPlayer] 恢复播放失败:', error);
                // 恢复失败，导航到详情页重新播放
                navigateToCurrentAttraction();
              } else {
                resume(); // 使用 resume() 而不是 play()，保持 currentAttraction 数据不变
              }
            },
            () => {
              // 播放完成
              stop();
            },
          );
        } else {
          // 没有音频对象或不是暂停状态，导航到详情页
          navigateToCurrentAttraction();
        }
      }
    } catch (error) {
      console.error('❌ [GlobalAudioPlayer] 操作失败:', error);
    }
  };

  // 处理关闭按钮点击 - 完全停止播放并清除状态
  const handleClose = async () => {
    try {
      await voiceService.stopAudio();
      stop(); // 清除全局播放状态
    } catch (error) {
      console.error('❌ 停止播放失败:', error);
      // 即使停止失败，也要清除全局状态
      stop();
    }
  };

  // 处理控制条点击 - 返回详情页
  const handleBarPress = () => {
    navigateToCurrentAttraction();
  };

  if (!shouldShow) {
    return null;
  }

  // 计算滑动位置
  const translateY = slideAnim.interpolate({
    inputRange: [0, 1],
    outputRange: [100, 0], // 从下方100像素滑入到0位置
  });

  return (
    <Animated.View
      style={[
        styles.container,
        {
          transform: [{ translateY }],
        },
      ]}
    >
      <TouchableOpacity
        style={styles.barContent}
        onPress={handleBarPress}
        activeOpacity={0.8}
      >
        {/* 景区封面图 */}
        {currentAttraction.coverImage &&
        currentAttraction.coverImage !== 'null' &&
        currentAttraction.coverImage !== '' ? (
          <Animated.Image
            source={{ uri: currentAttraction.coverImage }}
            style={[
              styles.coverImage,
              {
                transform: [
                  {
                    rotate: rotateAnim.interpolate({
                      inputRange: [0, 1],
                      outputRange: ['0deg', '360deg'],
                    }),
                  },
                ],
              },
            ]}
          />
        ) : (
          <View style={[styles.coverImage, styles.placeholderImage]}>
            <Icon name="image-outline" size={24} color="#999" />
          </View>
        )}

        {/* 景区名称 */}
        <View style={styles.infoContainer}>
          <Text style={styles.attractionName} numberOfLines={1}>
            {currentAttraction.name || currentAttraction.areaName || '景区音频'}
          </Text>
          <Text style={styles.statusText}>
            {isPlaying ? '正在播放...' : '已暂停'}
          </Text>
        </View>

        {/* 播放/暂停按钮 */}
        <TouchableOpacity
          style={styles.controlButton}
          onPress={handlePlayPause}
          activeOpacity={0.7}
        >
          <Icon
            name={isPlaying ? 'pause' : 'play'}
            size={24}
            color={COLORS.white}
          />
        </TouchableOpacity>

        {/* 关闭按钮 */}
        <TouchableOpacity
          style={styles.closeButton}
          onPress={handleClose}
          activeOpacity={0.7}
        >
          <Icon name="close" size={22} color={COLORS.white} />
        </TouchableOpacity>
      </TouchableOpacity>
    </Animated.View>
  );
};

const styles = StyleSheet.create({
  container: {
    position: 'absolute',
    bottom: Platform.OS === 'ios' ? 85 : 60, // 导航栏高度
    left: 0,
    right: 0,
    height: 70,
    zIndex: 1000,
    elevation: 10, // Android 阴影
  },
  barContent: {
    flex: 1,
    flexDirection: 'row',
    alignItems: 'center',
    backgroundColor: 'rgba(30, 30, 30, 0.95)', // 半透明深色背景
    paddingHorizontal: SPACING.md,
    paddingVertical: SPACING.sm,
    borderTopWidth: 1,
    borderTopColor: 'rgba(255, 255, 255, 0.1)',
    shadowColor: COLORS.shadow,
    shadowOffset: {
      width: 0,
      height: -2,
    },
    shadowOpacity: 0.3,
    shadowRadius: 4,
  },
  coverImage: {
    width: 50,
    height: 50,
    borderRadius: 25,
    backgroundColor: COLORS.background.secondary,
    marginRight: SPACING.md,
  },
  placeholderImage: {
    justifyContent: 'center',
    alignItems: 'center',
    backgroundColor: COLORS.black,
  },
  infoContainer: {
    flex: 1,
    justifyContent: 'center',
  },
  attractionName: {
    fontSize: 16,
    fontWeight: '600',
    color: COLORS.white,
    marginBottom: 4,
  },
  statusText: {
    fontSize: 13,
    color: 'rgba(255, 255, 255, 0.7)',
  },
  controlButton: {
    width: 44,
    height: 44,
    borderRadius: 22,
    backgroundColor: COLORS.primary,
    justifyContent: 'center',
    alignItems: 'center',
    marginRight: SPACING.sm,
  },
  closeButton: {
    width: 36,
    height: 36,
    borderRadius: 18,
    backgroundColor: 'rgba(255, 255, 255, 0.15)',
    justifyContent: 'center',
    alignItems: 'center',
  },
});

export default GlobalAudioPlayer;
